#include "StdAfx.h"

#include <cassert>

#include "AceEnvironment.h"

#include "AceException.h"
#include "AceSessionImpl.h"

namespace ace
{
  CAceEnvironment::CSessionMap CAceEnvironment::s_sessions;

  CAceEnvironment::CAceEnvironment()
  {
    AceCheck(AceInitialize(), "Failed to initialize ACE API library.");
  }

  CAceEnvironment::~CAceEnvironment()
  {
    AceCheck(AceShutdown(&CAceEnvironment::destroySession), "Failed to shutdown ACE API library.");
  }  

  void CAceEnvironment::clear() const
  {
    AceCleanup(&CAceEnvironment::destroySession);
  }  

  auth::IAuthSession *CAceEnvironment::createSession()
  {
    return new ace::impl::CAceSessionImpl(*this);
  }

  void WINAPI CAceEnvironment::destroySession(SDI_HANDLE handle)
  {
    CSessionMap::iterator itSession = s_sessions.find(handle);

    if(itSession != s_sessions.end())
      itSession->second->close();
  }

  void CAceEnvironment::registerSession(IAceSession *pSession)
  {
    assert(pSession);
    assert(pSession->isOpen());

    s_sessions[pSession->getHandle()] = pSession;
  }

  void CAceEnvironment::unregisterSession(IAceSession *pSession)
  {
    assert(pSession);
    assert(!pSession->isOpen());

    s_sessions.erase(pSession->getHandle());
  }
}